package dk.pervasivepositioning.project2;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;

public class PeriodicStrategy extends ReportingStrategy {

	private Timer t;
	private int timeperiod;

	public PeriodicStrategy(String URL, int timeperiod, LocationManager lm,
			Activity activity) throws IOException {
		super(URL);
		this.timeperiod = timeperiod;
		this.lm = lm;
		this.activity = activity;
	}

	final Handler handler = new Handler();

	TimerTask timerTask = new TimerTask() {
		public void run() {
			handler.post(new Runnable() {
				public void run() {
					startUpdates();
				}
			});
		}
	};

	public void startup() {
		t = new Timer();
		t.schedule(timerTask, 0, timeperiod);
	}

	@Override
	public void shutdown() {
		t.cancel();
		super.stopUpdates();
	}

	@Override
	public void stopUpdates() {
		super.stopUpdates();
		t.cancel();
	}

	@Override
	public void receivedLocation(Location location) {
		super.stopUpdates();
		try {
			super.sendData(location);
		} catch (Exception e) {
			printDebugInfo(e.getMessage() + "\n");

		}
	}

	@Override
	public String getStrategy() {
		return "periodic";
	}
}
